<template>
  <div class="show-page">
    <div class="container mx-auto px-4 py-8">
      <!-- 筛选条件 -->
      <el-card class="filter-card mb-6">
        <el-form label-width="80px">
          <!-- 类型筛选 -->
          <el-form-item label="按类型">
            <div class="filter-tags">
              <el-tag
                :type="!selectedGenre ? 'success' : 'info'"
                class="filter-tag"
                @click="selectGenre(null)"
              >
                全部
              </el-tag>
              <el-tag
                v-for="genre in genres"
                :key="genre.genreId"
                :type="selectedGenre === genre.genreId ? 'success' : 'info'"
                class="filter-tag"
                @click="selectGenre(genre.genreId)"
              >
                {{ genre.name }}
              </el-tag>
            </div>
          </el-form-item>

          <!-- 地区筛选 -->
          <el-form-item label="按地区">
            <div class="filter-tags">
              <el-tag
                :type="!selectedCountry ? 'success' : 'info'"
                class="filter-tag"
                @click="selectCountry(null)"
              >
                全部
              </el-tag>
              <el-tag
                v-for="country in countries"
                :key="country.countryId"
                :type="selectedCountry === country.countryId ? 'success' : 'info'"
                class="filter-tag"
                @click="selectCountry(country.countryId)"
              >
                {{ country.name }}
              </el-tag>
            </div>
          </el-form-item>

          <!-- 年份筛选 -->
          <el-form-item label="按年份">
            <div class="filter-tags">
              <el-tag
                :type="!selectedYear ? 'success' : 'info'"
                class="filter-tag"
                @click="selectYear(null)"
              >
                全部
              </el-tag>
              <el-tag
                v-for="year in years"
                :key="year"
                :type="selectedYear === year ? 'success' : 'info'"
                class="filter-tag"
                @click="selectYear(year)"
              >
                {{ year }}
              </el-tag>
              <el-tag
                :type="selectedYear === -1 ? 'success' : 'info'"
                class="filter-tag"
                @click="selectYear(-1)"
              >
                更早
              </el-tag>
            </div>
          </el-form-item>

          <!-- 语言筛选 -->
          <el-form-item label="按语言">
            <div class="filter-tags">
              <el-tag
                :type="!selectedLanguage ? 'success' : 'info'"
                class="filter-tag"
                @click="selectLanguage(null)"
              >
                全部
              </el-tag>
              <el-tag
                v-for="lang in languages"
                :key="lang.languageId"
                :type="selectedLanguage === lang.name ? 'success' : 'info'"
                class="filter-tag"
                @click="selectLanguage(lang.name)"
              >
                {{ lang.name }}
              </el-tag>
            </div>
          </el-form-item>

          <!-- 排序方式 -->
          <el-form-item label="排序">
            <el-radio-group v-model="orderBy" @change="handleOrderChange">
              <el-radio-button label="createTime">按时间</el-radio-button>
              <el-radio-button label="hits">按人气</el-radio-button>
              <el-radio-button label="rating">按评分</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 影片列表 -->
      <div v-if="loading && movies.length === 0" class="grid grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
        <el-skeleton v-for="i in 12" :key="i" animated>
          <template #template>
            <el-skeleton-item variant="image" style="width: 100%; height: 240px" />
            <el-skeleton-item variant="text" class="mt-2" />
            <el-skeleton-item variant="text" class="mt-1" />
          </template>
        </el-skeleton>
      </div>

      <div v-else class="grid grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
        <MovieCard
          v-for="movie in movies"
          :key="movie.movieBasicsId"
          :movie="movie"
        />
      </div>

      <!-- 空状态 -->
      <el-empty v-if="!loading && movies.length === 0" description="暂无影片" />

      <!-- 加载更多 -->
      <div v-if="hasMore" ref="loadMoreRef" class="text-center py-8">
        <el-icon v-if="loadingMore" class="is-loading" :size="24">
          <Loading />
        </el-icon>
      </div>

      <!-- 已加载全部 -->
      <div v-if="!hasMore && movies.length > 0" class="text-center py-4 text-gray-400">
        已加载全部影片
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Loading } from '@element-plus/icons-vue'

const route = useRoute()
const columnValue = computed(() => route.params.columnValue as string)

// 筛选条件
const selectedGenre = ref<number | null>(null)
const selectedCountry = ref<number | null>(null)
const selectedYear = ref<number | null>(null)
const selectedLanguage = ref<string | null>(null)
const orderBy = ref('createTime')

// 分页
const currentPage = ref(1)
const pageSize = ref(24)
const total = ref(0)
const hasMore = ref(true)

// 数据
const loading = ref(false)
const loadingMore = ref(false)
const movies = ref<any[]>([])
const genres = ref<any[]>([])
const countries = ref<any[]>([])
const languages = ref<any[]>([])

// 年份选项（最近20年）
const years = computed(() => {
  const currentYear = new Date().getFullYear()
  const yearList: number[] = []
  for (let i = 0; i <= 20; i++) {
    yearList.push(currentYear - i)
  }
  return yearList
})

// 加载更多元素引用
const loadMoreRef = ref()

// 获取筛选选项
const fetchFilters = async () => {
  try {
    const [genresData, countriesData, languagesData] = await Promise.all([
      $fetch(`/dev-api/app/movieapp/genres`, {
        params: { columnValue: columnValue.value }
      }),
      $fetch('/dev-api/app/basic/countries'),
      $fetch('/dev-api/app/basic/languages')
    ])

    // /app/** 接口直接返回数组或 {rows: []} 格式
    genres.value = Array.isArray(genresData) ? genresData : (genresData.rows || [])
    countries.value = Array.isArray(countriesData) ? countriesData : (countriesData.rows || [])
    languages.value = Array.isArray(languagesData) ? languagesData : (languagesData.rows || [])
  } catch (error) {
    console.error('获取筛选选项失败:', error)
  }
}

// 获取影片列表
const fetchMovies = async (append = false) => {
  if (append) {
    loadingMore.value = true
  } else {
    loading.value = true
  }

  try {
    const data: any = await $fetch('/dev-api/app/movieapp/list', {
      params: {
        columnValue: columnValue.value,
        genreId: selectedGenre.value,
        countryId: selectedCountry.value,
        year: selectedYear.value,
        language: selectedLanguage.value,
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        status: '0'
      }
    })

    // /app/** 接口返回 {rows: [], total: number} 格式
    const newMovies = data.rows || []

    if (append) {
      movies.value = [...movies.value, ...newMovies]
    } else {
      movies.value = newMovies
    }

    total.value = data.total || 0
    hasMore.value = movies.value.length < total.value
  } catch (error) {
    console.error('获取影片列表失败:', error)
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

// 重新加载（重置分页）
const reload = () => {
  currentPage.value = 1
  fetchMovies(false)
}

// 筛选操作
const selectGenre = (genreId: number | null) => {
  selectedGenre.value = genreId
  reload()
}

const selectCountry = (countryId: number | null) => {
  selectedCountry.value = countryId
  reload()
}

const selectYear = (year: number | null) => {
  selectedYear.value = year
  reload()
}

const selectLanguage = (language: string | null) => {
  selectedLanguage.value = language
  reload()
}

const handleOrderChange = () => {
  reload()
}

// 加载更多
const loadMore = () => {
  if (hasMore.value && !loadingMore.value) {
    currentPage.value++
    fetchMovies(true)
  }
}

// 监听滚动到底部
onMounted(() => {
  const observer = new IntersectionObserver((entries) => {
    if (entries[0].isIntersecting) {
      loadMore()
    }
  }, {
    threshold: 0.1
  })

  if (loadMoreRef.value) {
    observer.observe(loadMoreRef.value)
  }

  onUnmounted(() => {
    observer.disconnect()
  })
})

// 初始化
onMounted(async () => {
  await fetchFilters()
  await fetchMovies()
})

// SEO
useSeoMeta({
  title: `${columnValue.value}筛选`,
  description: `按类型、地区、年份、语言筛选${columnValue.value}`
})
</script>

<style scoped>
.show-page {
  min-height: 100vh;
  background-color: #0f0f0f;
  padding-top: 80px;
}

.filter-card {
  background-color: rgba(31, 41, 55, 0.8);
  border: 1px solid rgba(55, 65, 81, 0.5);
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-form-item__label) {
  color: rgba(255, 255, 255, 0.8);
}

.filter-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.filter-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.filter-tag:hover {
  transform: translateY(-2px);
}

:deep(.el-tag--success) {
  background-color: #10b981;
  border-color: #10b981;
  color: white;
}

:deep(.el-tag--info) {
  background-color: rgba(55, 65, 81, 0.5);
  border-color: rgba(55, 65, 81, 0.8);
  color: rgba(255, 255, 255, 0.8);
}

:deep(.el-radio-button__inner) {
  background-color: transparent;
  border-color: rgba(55, 65, 81, 0.8);
  color: rgba(255, 255, 255, 0.8);
}

:deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
  background-color: #10b981;
  border-color: #10b981;
  color: white;
  box-shadow: none;
}
</style>
